package Thought;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import org.dom4j.DocumentException;

import Discount.Discount;
import Discount.DiscountService;
import Goods.Goods;
import Goods.GoodsService;
import Inventory.InventoryService;

public class Service implements ServiceInterface{

//	private Map<String, Double> list;
//	private Map<String, ArrayList<String>> Items;
	
	public Service() throws DocumentException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		// TODO Auto-generated constructor stub
				
		Class<?> goodsService=Class.forName(Config.getGoodsServicePath());
		Class<?> discountService=Class.forName(Config.getDiscountServicePath());
		Class<?> inventoryService=Class.forName(Config.getInventoryServicePath());		
		String data = Ask();
		
		Map<String, ArrayList<String>> Items = ItemXML();		
		Map<String, Double> list = ParseData(data);				
				
		GoodsService goodservicce= (GoodsService) goodsService.newInstance();
		Map<String,Goods> goods=goodservicce.Init(Items, list);	
		
		
		DiscountService discservice=(DiscountService) discountService.newInstance();		
		Discount discount=discservice.Init(goods);
		
		
		InventoryService inveservice=(InventoryService) inventoryService.newInstance();
		inveservice.Show(goods, discount);
		
	}
	
	@Override
	public Map<String, ArrayList<String>> ItemXML() throws DocumentException {
		// TODO Auto-generated method stub				
		return new XmlParser(Config.getItemXmlPath()).getLIST();
	}
	@Override
	public Map<String, Double> ParseData(String data) {
		// TODO Auto-generated method stub
		String ITEM = "[^ITEM\\d{6,12}$]";
		Map<String, Double> list=new TreeMap<>();
		data = data.replaceAll(ITEM, "");
		ITEM="";
		int f = 0, l = 0;
		for (int i = 0; i < data.length(); i++) {
			if (data.charAt(i) == 'I')
				f = i;
			else if (data.charAt(i) == ',')
				l = i;
			if (l <= f&&i!=data.length()-1) {
				ITEM += data.charAt(i);
			} else {						
				if(i==data.length()-1)
					ITEM+=data.charAt(i);
				String code=ITEM.equals("")?ITEM:ITEM.substring(0,10);
				double amount=ITEM.length()>10?Double.parseDouble(ITEM.substring(10, ITEM.length())):1.0;
				if(list.containsKey(code)){
					list.put(code,list.get(ITEM)+amount);					
				}else{										
					list.put(code, amount);
				}				
				ITEM = "";
			}			
		}
		return list;
	}
	private String Ask() throws IOException {
		// TODO Auto-generated method stub
		System.out.println("请在一行输入购买方案：");
		BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
		String data =sc.readLine();
		data=data.trim();
		return data;
	}
	
}
